//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;
using System.Collections.Generic;

/// <summary>
/// Stores database specific methods
/// </summary>
namespace CodePlex.GpsTracker.DatabaseLayer
{
    public class GpsDataStoreDatabaseLayer
    {
        public static string SaveGpxXml(string userName, string name, string description, string gpxXml)
        {
            return SaveGpxXml("00000000-0000-0000-0000-000000000000", userName, name, description, gpxXml);
        }

        public static string SaveGpxXml(string gpxGuid, string userName, string name, string description, string gpxXml)
        {
            SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["mainConnection"].ConnectionString);

            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = cnn;
                cmd.CommandText = "gpsdatastore.SaveGpx";
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter p = new SqlParameter("@GpxGuid", SqlDbType.Char, 36);
                p.Value = gpxGuid;
                p.Direction = ParameterDirection.InputOutput;

                cmd.Parameters.Add(p);
                cmd.Parameters.Add(new SqlParameter("@Name", name));
                cmd.Parameters.Add(new SqlParameter("@Description", description));

                p = new SqlParameter("@XmlData", SqlDbType.Xml);
                p.Value = gpxXml;
                cmd.Parameters.Add(p);

                cmd.Parameters.Add(new SqlParameter("@UserName", userName));

                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
                cmd.Connection.Close();


                gpxGuid = (string)cmd.Parameters["@GpxGuid"].Value;
            }

            return gpxGuid;
        }

        public static string GetGpxByGuid(string guid)
        {
            string gpx = null;

            SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["mainConnection"].ConnectionString);

            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = cnn;
                cmd.CommandText = "gpsdatastore.GetGpxByGuid";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new SqlParameter("@GpxGuid", guid));

                cmd.Connection.Open();
                object o = cmd.ExecuteScalar();
                cmd.Connection.Close();

                if (o != null)
                {
                    gpx = (string)o;
                }
            }

            return gpx;
        }
    }
}
